<template>
  <div class="inventory-status">
    <Card title="库存状态管理" :bordered="false">
      <div class="status-header">
        <Row :gutter="16">
          <Col :span="6">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="搜索资源名称、编码"
              allow-clear
              @change="handleSearch"
            />
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.resourceType"
              placeholder="资源类型"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="PHYSICAL">物理资源</SelectOption>
              <SelectOption value="DIGITAL">数字资源</SelectOption>
              <SelectOption value="SERVICE">服务资源</SelectOption>
            </Select>
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.status"
              placeholder="库存状态"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="NORMAL">正常</SelectOption>
              <SelectOption value="LOW">低库存</SelectOption>
              <SelectOption value="OUT">缺货</SelectOption>
              <SelectOption value="OVERSTOCK">积压</SelectOption>
            </Select>
          </Col>
          <Col :span="10">
            <Space>
              <Button type="primary" @click="handleSearch">搜索</Button>
              <Button @click="handleReset">重置</Button>
              <Button type="primary" @click="openInventoryForm('create')">
                新增库存
              </Button>
              <Button @click="exportInventory">导出</Button>
            </Space>
          </Col>
        </Row>
      </div>

      <div class="status-overview">
        <Row :gutter="16">
          <Col :span="6">
            <Statistic
              title="总库存项"
              :value="overview.total"
              :value-style="{ color: '#1890ff' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="正常库存"
              :value="overview.normal"
              :value-style="{ color: '#52c41a' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="低库存预警"
              :value="overview.low"
              :value-style="{ color: '#faad14' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="缺货"
              :value="overview.out"
              :value-style="{ color: '#ff4d4f' }"
            />
          </Col>
        </Row>
      </div>

      <div class="status-content">
        <Table
          :columns="columns"
          :data-source="inventoryList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'resourceType'">
              <Tag :color="getResourceTypeColor(record.resourceType)">
                {{ getResourceTypeText(record.resourceType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'quantity'">
              <span :class="getQuantityClass(record)">
                {{ record.quantity }}
              </span>
            </template>
            <template v-else-if="column.key === 'usageRate'">
              <Progress
                :percent="record.usageRate"
                :status="getProgressStatus(record.usageRate)"
                size="small"
              />
            </template>
            <template v-else-if="column.key === 'action'">
              <Space>
                <Button type="link" size="small" @click="viewInventory(record)">
                  查看
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="openInventoryForm('edit', record)"
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="adjustInventory(record)"
                >
                  调整
                </Button>
                <Button type="link" size="small" @click="viewHistory(record)">
                  历史
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </div>
    </Card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Progress,
  Row,
  Select,
  SelectOption,
  Space,
  Statistic,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const inventoryList = ref<any[]>([]);
const total = ref(0);

const searchForm = reactive({
  keyword: '',
  resourceType: '',
  status: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const overview = reactive({
  total: 0,
  normal: 0,
  low: 0,
  out: 0,
});

const columns = [
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '资源编码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '资源类型',
    dataIndex: 'resourceType',
    key: 'resourceType',
    width: 120,
  },
  {
    title: '当前库存',
    dataIndex: 'quantity',
    key: 'quantity',
    width: 100,
  },
  {
    title: '最小库存',
    dataIndex: 'minQuantity',
    key: 'minQuantity',
    width: 100,
  },
  {
    title: '最大库存',
    dataIndex: 'maxQuantity',
    key: 'maxQuantity',
    width: 100,
  },
  {
    title: '使用率',
    dataIndex: 'usageRate',
    key: 'usageRate',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '最后更新',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 模拟数据
const mockInventory = [
  {
    id: '1',
    name: '豪华套房',
    code: 'ROOM_001',
    resourceType: 'PHYSICAL',
    quantity: 5,
    minQuantity: 2,
    maxQuantity: 10,
    usageRate: 85,
    status: 'NORMAL',
    updateTime: '2024-01-15 10:30:00',
  },
  {
    id: '2',
    name: '温泉池',
    code: 'POOL_001',
    resourceType: 'PHYSICAL',
    quantity: 1,
    minQuantity: 2,
    maxQuantity: 5,
    usageRate: 95,
    status: 'LOW',
    updateTime: '2024-01-15 09:15:00',
  },
  {
    id: '3',
    name: 'VIP包间',
    code: 'VIP_001',
    resourceType: 'PHYSICAL',
    quantity: 0,
    minQuantity: 1,
    maxQuantity: 3,
    usageRate: 100,
    status: 'OUT',
    updateTime: '2024-01-15 08:45:00',
  },
  {
    id: '4',
    name: '数字会议室',
    code: 'DIGITAL_001',
    resourceType: 'DIGITAL',
    quantity: 8,
    minQuantity: 5,
    maxQuantity: 10,
    usageRate: 80,
    status: 'NORMAL',
    updateTime: '2024-01-15 11:20:00',
  },
  {
    id: '5',
    name: '按摩服务',
    code: 'SERVICE_001',
    resourceType: 'SERVICE',
    quantity: 12,
    minQuantity: 10,
    maxQuantity: 15,
    usageRate: 75,
    status: 'NORMAL',
    updateTime: '2024-01-15 10:00:00',
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));

    let filteredData = mockInventory;

    if (searchForm.keyword) {
      filteredData = filteredData.filter(
        (item) =>
          item.name.includes(searchForm.keyword) ||
          item.code.includes(searchForm.keyword),
      );
    }

    if (searchForm.resourceType) {
      filteredData = filteredData.filter(
        (item) => item.resourceType === searchForm.resourceType,
      );
    }

    if (searchForm.status) {
      filteredData = filteredData.filter(
        (item) => item.status === searchForm.status,
      );
    }

    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;

    inventoryList.value = filteredData.slice(start, end);
    total.value = filteredData.length;
    pagination.total = total.value;

    // 更新概览数据
    updateOverview(filteredData);
  } catch (error) {
    console.warn('加载库存数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 更新概览数据
const updateOverview = (data: any[]) => {
  overview.total = data.length;
  overview.normal = data.filter((item) => item.status === 'NORMAL').length;
  overview.low = data.filter((item) => item.status === 'LOW').length;
  overview.out = data.filter((item) => item.status === 'OUT').length;
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    resourceType: '',
    status: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 打开库存表单
const openInventoryForm = (type: 'create' | 'edit', record?: any) => {
  message.info(`${type === 'create' ? '新增' : '编辑'}库存功能开发中...`);
};

// 查看库存
const viewInventory = (record: any) => {
  message.info(`查看库存"${record.name}"功能开发中...`);
};

// 调整库存
const adjustInventory = (record: any) => {
  message.info(`调整库存"${record.name}"功能开发中...`);
};

// 查看历史
const viewHistory = (record: any) => {
  message.info(`查看库存历史"${record.name}"功能开发中...`);
};

// 导出库存
const exportInventory = () => {
  message.success('库存数据导出成功');
};

// 工具函数
const getResourceTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    PHYSICAL: 'blue',
    DIGITAL: 'green',
    SERVICE: 'orange',
  };
  return colors[type] || 'default';
};

const getResourceTypeText = (type: string) => {
  const texts: Record<string, string> = {
    PHYSICAL: '物理资源',
    DIGITAL: '数字资源',
    SERVICE: '服务资源',
  };
  return texts[type] || type;
};

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    NORMAL: 'green',
    LOW: 'orange',
    OUT: 'red',
    OVERSTOCK: 'purple',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    NORMAL: '正常',
    LOW: '低库存',
    OUT: '缺货',
    OVERSTOCK: '积压',
  };
  return texts[status] || status;
};

const getQuantityClass = (record: any) => {
  if (record.quantity <= record.minQuantity) return 'quantity-low';
  if (record.quantity >= record.maxQuantity) return 'quantity-high';
  return 'quantity-normal';
};

const getProgressStatus = (rate: number) => {
  if (rate >= 90) return 'exception';
  if (rate >= 70) return 'active';
  return 'normal';
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.inventory-status {
  padding: 20px;
}

.status-header {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.status-overview {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.status-content {
  margin-bottom: 24px;
}

.quantity-normal {
  color: #52c41a;
  font-weight: bold;
}

.quantity-low {
  color: #faad14;
  font-weight: bold;
}

.quantity-high {
  color: #ff4d4f;
  font-weight: bold;
}
</style>
